<?php
require_once ("Connection/DB_Connection.php");

class UserHandler {
	const Username = "username";
	const Password = "password";

	public function DoCreateNewUser($name,$firstname,$lastname, $password) {//.inloggning...

		if ($this -> DoInsertNewUser($name,$firstname,$lastname, $password)) {
			$_SESSION[self::Username] = $name;

			return true;

		}
		return false;
	}

	public function DoInsertNewUser($name,$lastname, $password) {
		//tar kontakt med databasen
		$DBConnection = new DBConnection();
		$DBConnection -> Connect();

		//ställer en sql-fråga.
		$sql = "INSERT INTO `user`(`m_pk`, `m_username`, `lastname`, `m_password`) VALUES ('',?,?,?)";
		

		$stmt = $DBConnection -> prepare($sql);
		$stmt -> bind_param("sss", $name,$lastname, $password);

		if ($stmt === FALSE) {
			
			return false;
		}
		$stmt -> execute();
		// ger resultet.
		$result = $stmt -> get_result();

		$stmt -> close();
		return false;
	}
		public function controllDB($name, $password) {
		
		//tar kontakt med databasen
		$DBConnection = new DBConnection();
		$DBConnection -> Connect();

		//ställer en sql-fråga.
		$sql = 'SELECT * FROM `user` WHERE m_username=? And m_password=? LIMIT 0,30';

		$stmt = $DBConnection -> prepare($sql);
		$stmt -> bind_param("ss", $name, $password);

		if ($stmt === FALSE) {
			//echoBr("prepare of '$sql' failed " .  $DBConnection -> error);
			return false;
		}
		$stmt -> execute();
		
		while($stmt->fetch()){
			$stmt -> close();
			return true;
			
		}
		$stmt -> close();
		// ger resultet.
		/*
		$result = $stmt -> get_result();

		while ($row = $result -> fetch_array(MYSQLI_NUM)) {
			$stmt -> close();
			return true;
		}
		 */
		
		return false;
		
	}

	public function DeleteUser($name) {
		//tar kontakt med databasen
		$DBConnection = new DBConnection();
		$DBConnection -> Connect();

		//ställer en sql-fråga.
		$sql = "DELETE FROM `user` WHERE `m_username` = ?";

		$stmt = $DBConnection -> prepare($sql);
		$stmt -> bind_param("s", $name);

		if ($stmt === FALSE) {
			//echoBr("prepare of '$sql' failed " .  $DBConnection -> error);
			return false;
		}
		$stmt -> execute();
		// ger resultet.
		$result = $stmt -> get_result();
		/*
		 while ($row = $result -> fetch_array(MYSQLI_NUM)) {
		 $stmt -> close();
		 return true;
		 }
		 *
		 */
		$stmt -> close();
		return false;
	}

	public function testRegister() {
		$this -> DoLogout();

		//Nya användare får inte ha tomt användarnamn.
		if ($this -> DoCreateNewUser('', '')) {
			echo "inloggad efter inloggning med fel uppgifter, fel på dologin eller isloggedin";
			return false;
		}
		//Lösenorden skall ha en minimilängd på 6 tecken
		if ($this -> DoCreateNewUser('kalle', '123Abc')) {
			echo "fel vid dologin.";
			return false;
		}

		if ($this -> DeleteUser('kalle')) {
			echo "fel vid dologin.";
			return false;
		}

		return True;

	}

}
